package thomas.studio.spring.security.ldap.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.AuthenticationSource;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

import thomas.studio.spring.security.ldap.config.property.LdapProperty;

@Configuration
@EnableConfigurationProperties(LdapProperty.class)
public class LdapConfig {
	
	@Autowired
	private LdapProperty ldapProperty;
	
	@Bean
	public LdapTemplate ldapTemplate(){
		LdapTemplate ldapTemplate = new LdapTemplate();
		ldapTemplate.setContextSource(ldapContextSource());
		return ldapTemplate;
	}

	@Bean
	public LdapContextSource ldapContextSource() {
		LdapContextSource ldapContextSource = new LdapContextSource();
		ldapContextSource.setCacheEnvironmentProperties(false);
	    ldapContextSource.setUrl(ldapProperty.getUrl());
	    ldapContextSource.setBase(ldapProperty.getBase());
/*	    ldapContextSource.setUserDn(ldapProperty.getUserDn());
	    ldapContextSource.setPassword(ldapProperty.getPassword());*/
	    
	    ldapContextSource.setAuthenticationSource(new AuthenticationSource() {
	        @Override
		public String getCredentials() {
		    return ldapProperty.getPassword();
		}
	 
		@Override
		public String getPrincipal() {
		    return ldapProperty.getUserDn();
		}
	    });
	    
		return ldapContextSource;
	}
}
